package com.telrob.bytevm.natives.simp;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.telrob.bytevm.natives.NativeMethod;
import com.telrob.bytevm.vm.Param;
import com.telrob.bytevm.vm.Register;
import com.telrob.bytevm.vm.VM;

public class Print {
	
	@NativeMethod("vm_gpio")
	public static void gpio(Param param) {
		int port=param.getIntParam(0);
		int state=param.getIntParam(1);
		System.err.println("port:"+port+",state:"+state);
	}
	
	@NativeMethod("vm_gpio_mode")
	public static void vm_gpio_mode(Param param) {
		int port=param.getIntParam(0);
		int state=param.getIntParam(1);
		System.err.println("vm_gpio_mode:"+port+","+state);
	}
	
	@NativeMethod("vm_sleep")
	public static void sleep(Param param) {
		int time=param.getIntParam(0);
		try {
			Thread.sleep(time);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@NativeMethod("createTask")
	public static void createTask(Param param) {
		//获取堆栈的位置
		int index=param.getIntParam(0);
		//获取函数的位置
		int pc=param.getIntParam(1);
		Register R=new Register();
		R.SS=index;
		R.PC=pc;
		VM.addTask(R);
	}
	
	@NativeMethod("print")
	public static void print(Param param) {
		try {
			//System.err.println("****************");
			int size=param.getParamSize();
			String str=param.getStringParam(0);
			if(size>1) {
				Pattern p=Pattern.compile("%[0-9]*[scbdoxXf]{1}");
				List<String>clist=new ArrayList<String>();
				Matcher m=p.matcher(str);
				while(m.find()) {
					String d=m.group(0);
					clist.add(d);
				}
				Object[]obj=new Object[size-1];
				for(int i=0;i<size-1;i++) {
					if(i<clist.size()) {
						String ss=clist.get(i);
						if(ss.endsWith("s")) {
							obj[i]=param.getStringParam(i+1);
						}else if(ss.endsWith("d")||ss.endsWith("X")
								||ss.endsWith("x")||ss.endsWith("o")
								||ss.endsWith("b")) {
							obj[i]=param.getIntParam(i+1);
						}else if(ss.endsWith("c")) {
							obj[i]=param.getCharParam(i+1);
						}
					}else {
						obj[i]=0;
					}
				}
				str=String.format(str, obj);
			}
			System.err.print(str);
			//System.err.println(param);
			//System.err.println("-----------------");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		char a='A';
		int b=a;
		System.err.println(b);
	}
	
}
